package com.netposa.datawarehouse.aggregator.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netposa.appwebres.common.WebResInfo;
import com.netposa.appwebres.exception.WebResException;
import com.netposa.datawarehouse.aggregator.config.AggregatorProperties;
import com.netposa.datawarehouse.aggregator.factory.SearchDataFactory;
import com.netposa.datawarehouse.aggregator.factory.service.SearchData;
import com.netposa.datawarehouse.aggregator.portrait.model.DataBean;
import com.netposa.datawarehouse.aggregator.portrait.model.PortraitCondition;
import com.netposa.datawarehouse.aggregator.portrait.model.PortraitSearchCondition;
import com.netposa.datawarehouse.aggregator.search.ResourceParam;
import com.netposa.datawarehouse.aggregator.search.ResourceResult;
import com.netposa.datawarehouse.aggregator.service.AggregatorService;
import com.netposa.datawarehouse.aggregator.service.ImgSearchService;
import com.netposa.datawarehouse.aggregator.thirdService.AnalysisServiceFeign;
import com.netposa.datawarehouse.aggregator.util.ScoreRoundingMode;
import com.netposa.datawarehouse.aggregator.util.VehicleAttrContext;
import com.netposa.datawarehouse.aggregator.web.model.ExcludeCondition;
import com.netposa.datawarehouse.aggregator.web.model.SearchDataType;
import com.netposa.datawarehouse.aggregator.web.model.SessionDetection;
import com.netposa.datawarehouse.aggregator.web.vo.AllStructureVo;
import com.netposa.datawarehouse.aggregator.web.vo.DetectedResult;
import com.netposa.datawarehouse.aggregator.web.vo.DetectionResult;
import com.netposa.datawarehouse.aggregator.web.vo.FeatureDetectParam;
import com.netposa.datawarehouse.aggregator.web.vo.FeatureSearchParam;
import com.netposa.datawarehouse.aggregator.web.vo.FileSearchParam;
import com.netposa.datawarehouse.aggregator.web.vo.ImagePosition;
import com.netposa.datawarehouse.aggregator.web.vo.VehicleAttrVo;
import com.netposa.imageserver.client.ImageServerClient;
import com.netposa.imageserver.client.exception.ImageServerException;
import com.netposa.library.datawarehouse.aggregate.helper.ResourceDefined;
import com.netposa.library.datawarehouse.aggregate.helper.ResourceDefined.ResourceInnerFiled;
import com.netposa.library.datawarehouse.aggregate.helper.ResourceDefined.ResourceType;
import com.netposa.library.session.SessionManager;
import com.netposa.technicaltactics.client.FaceSearchImageClient;
import com.netposa.technicaltactics.client.HumanSearchImageClient;
import com.netposa.technicaltactics.client.NonmotorVehicleClient;
import com.netposa.technicaltactics.client.VehicleSearchImageClient;
import com.netposa.technicaltactics.common.FeatureSearch;
import com.netposa.technicaltactics.common.ImageSearchResult;
import com.netposa.technicaltactics.common.NewImageSearchCondition;
import com.netposa.technicaltactics.common.NewVehicleSearchCondition;
import com.netposa.technicaltactics.common.SearchFeatureCondition;
import com.netposa.technicaltactics.common.SearchImageCondition;
import com.netposa.technicaltactics.common.fileCommon.FileSearchCondition;
import com.netposa.technicaltactics.common.fileCommon.VehicleFileSearchCondition;
import com.netposa.technicaltactics.vehicle.VehicleInputRecord;
import com.netposa.vdt.pccclient.PccDetectClient;
import com.netposa.vdt.pccclient.autoconfigure.StructureTaskConfigProperties;
import com.netposa.vdt.pccclient.common.DataModel;
import com.netposa.vdt.pccclient.common.DetectBodyVehicleParam;
import com.netposa.vdt.pccclient.common.DetectFaceParam;
import com.netposa.vdt.pccclient.common.DetectResult;
import com.netposa.vdt.pccclient.common.ImageStruType;
import com.netposa.vdt.pccclient.common.ImageStructProcess;
import com.netposa.vdt.pccclient.common.VehicleGPUParam;
import com.netposa.vdt.pccclient.common.DataModel.DetectSwitch;
import com.netposa.vdt.pccclient.common.DataModel.FeatureSwitch;
import com.netposa.vdt.pccclient.common.DataModel.FeatureType;
import com.netposa.vdt.pccclient.common.DataModel.FilterRuleSwitch;
import com.netposa.vdt.pccclient.common.DataModel.OBJType;
import com.netposa.vdt.pccclient.exception.PccHandleException;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
@EnableConfigurationProperties({StructureTaskConfigProperties.class})
public class ImgSearchServiceImpl implements ImgSearchService {
   private static final Logger log = LoggerFactory.getLogger(ImgSearchServiceImpl.class);
   @Autowired
   private PccDetectClient PccDetectClient;
   @Autowired
   private ImageServerClient imageServerClient;
   @Autowired
   private SessionManager<LinkedHashMap<String, SessionDetection>> sessionManager;
   @Autowired
   private FaceSearchImageClient faceSearchImageClient;
   @Autowired
   private HumanSearchImageClient humanSearchImageClient;
   @Autowired
   private VehicleSearchImageClient vehicleSearchImageClient;
   @Autowired
   private AnalysisServiceFeign feign;
   @Autowired
   private AggregatorService aggregatorService;
   @Autowired
   private StructureTaskConfigProperties structureTaskConfigProperties;
   @Autowired
   private AggregatorProperties aggregatorProperties;
   @Autowired
   private NonmotorVehicleClient nonmotorVehicleClient;
   @Value("${netposa.image.gap.switch}")
   private Boolean gapSwitch;
   @Value("${netposa.image.gap.url}")
   private String gapUrl;

   public DetectionResult featureDetectNew(FeatureDetectParam featureDetectParam) throws PccHandleException, TException {
      String position = featureDetectParam.getPosition();
      String type = featureDetectParam.getType();
      String sessionKey = featureDetectParam.getSessionKey();
      MultipartFile file = featureDetectParam.getFile();
      String featureImg = featureDetectParam.getImgPath();
      if (this.gapSwitch != null && this.gapSwitch && StringUtils.isNotBlank(this.gapUrl)) {
         featureImg = this.gapUrl + featureImg;
         log.info("featureDetectNew  gapUrl = " + featureImg);
      }

      String jlbh = featureDetectParam.getJlbh();
      String featureBase64 = featureDetectParam.getFeatureBase64();
      SearchDataType dataType = SearchDataType.getEnumType(type);
      DetectResult detectResult;
      byte[] imgByte;
      if (StringUtils.isNoneBlank(jlbh)) {
         log.info("===>根据记录编号从大数据获取到特征");
         imgByte = this.searchByLog(dataType, new SearchFeatureCondition(jlbh, featureDetectParam.getAbsTime()));
         if (ArrayUtils.isNotEmpty(imgByte)) {
            detectResult = new DetectResult(imgByte);
            log.info("===>根据记录编号{}获取的特征:{}", jlbh, detectResult.getFeature());
         } else {
            log.info("根据记录编号从大数据没有获取到特征，重新提取特征");
            if (!StringUtils.isNoneBlank(featureImg)) {
               throw new WebResException("499", "参数不正确");
            }

            imgByte = this.imageServerClient.downloadImage(featureImg).getData();
            Pair data = this.detectAllTypes(imgByte, type, position);
            detectResult = (DetectResult)data.getValue();
            log.info("feature={}", ((DetectResult)data.getValue()).getFeature());
         }
      } else if (StringUtils.isNoneBlank(featureBase64)) {
         imgByte = Base64Utils.decodeFromString(featureBase64);
         detectResult = new DetectResult(imgByte);
      } else {
         if (file != null) {
            try {
               imgByte = file.getBytes();
            } catch (IOException var14) {
               throw new WebResException("499", "请上传文件");
            }

            featureImg = this.imageServerClient.uploadImage(imgByte);
         } else {
            if (!StringUtils.isNoneBlank(featureImg)) {
               throw new WebResException("499", "缺少文件或者图片路径");
            }

            if (StringUtils.isNoneBlank(position)) {
               featureImg = this.cutImage(featureImg, position);
            }

            imgByte = this.imageServerClient.downloadImage(featureImg).getData();
            log.info("===>图片url:{}", featureImg);
         }

         Pair data = this.detectAllTypes(imgByte, type, position);
         detectResult = (DetectResult)data.getValue();
         dataType = (SearchDataType)data.getKey();
         log.info("===>图片提取到的特征:{}", detectResult.getFeature());
      }

      if (StringUtils.isNoneBlank(position)) {
         featureImg = this.cutImage(featureImg, position);
      }

      log.info("特征长度：{}", detectResult.getFeatureLen());
      String dataKey = this.sessionManager.generKeyIfNoExist(featureDetectParam.getDataKey());
      sessionKey = this.setSessionCache(sessionKey, dataKey, new SessionDetection(dataType, detectResult, featureDetectParam.getFeatureType()));
      log.info("SessionKey={} : dataKey={}", sessionKey, dataKey);
      return new DetectionResult(sessionKey, dataKey, dataType, featureImg, detectResult.getFeature());
   }

   private String setSessionCache(String sessionKey, String dataKey, SessionDetection sessionDetection) {
      LinkedHashMap cache = this.getSessionDetection(sessionKey);
      if (cache == null) {
         cache = new LinkedHashMap();
      }

      cache.put(this.sessionManager.generKeyIfNoExist(dataKey), sessionDetection);
      String session = this.sessionManager.setValue(sessionKey, cache);
      return session;
   }

   public List<ResourceResult> fullSearch(FeatureSearchParam featureSearchParam) throws TException {
      if (StringUtils.isNotBlank(featureSearchParam.getFeature())) {
         Pair<SearchDataType, List<ImageSearchResult>> pair = this.queryBigDataByFeature(featureSearchParam);
         return this.queryData(pair.getKey(), pair.getValue(), featureSearchParam);
      } else {
         String sessionKey = featureSearchParam.getSessionKey();
         log.info("从redis中查询sessionKey={}下所有的dataKey", sessionKey);
         Map<String, SessionDetection> hash = this.getSessionDetection(sessionKey);
         log.info("SessionKey={} : SessionDetection={}", sessionKey, hash);
         if (hash != null && !hash.isEmpty()) {
            Pair<SearchDataType, List<ImageSearchResult>> pair = this.queryBigData(hash, featureSearchParam);
            return this.queryData(pair.getKey(), pair.getValue(), featureSearchParam);
         } else {
            log.info("失效的sessionKey={}", sessionKey);
            if (hash == null) {
               log.info("get value from redis is empty where sessionKey = {}", sessionKey);
            }

            throw new WebResException("499", "查询条件已经失效,请重新上传");
         }
      }
   }

   public List fullSearchImg(FileSearchParam fileSearchParam) throws TException {
      String sessionKey = fileSearchParam.getSessionKey();
      log.info("从redis中查询sessionKey={}下所有的dataKey", sessionKey);
      Map hash = this.getSessionDetection(sessionKey);
      if (hash != null && !hash.isEmpty()) {
         Pair pair = this.queryBigData(hash, fileSearchParam);
         return this.queryDataForFile((SearchDataType)pair.getKey(), (List)pair.getValue());
      } else {
         log.info("失效的sessionKey={}", sessionKey);
         if (hash == null) {
            log.info("get value from redis is empty where sessionKey = {}", sessionKey);
         }

         throw new WebResException("499", "查询条件已经失效,请重新上传");
      }
   }

   private LinkedHashMap<String, SessionDetection> getSessionDetection(String sessionKey) {
      return this.sessionManager.getValue(sessionKey);
   }

   public void cleanSession(String sessionkey) {
      this.sessionManager.invalidate(sessionkey);
   }

   public void cleanDetect(String sessionKey, String dataKey) {
      LinkedHashMap cache = this.sessionManager.getValue(sessionKey);
      if (cache != null) {
         SessionDetection sessionDetection = (SessionDetection)cache.remove(dataKey);
         log.info("移除dataKey:{} : {}", dataKey, sessionDetection);
         this.sessionManager.setValue(sessionKey, cache);
      }

   }

   private Pair<SearchDataType, List<ImageSearchResult>> queryBigData(final Map<String, SessionDetection> hash, final FeatureSearchParam featureSearchParam) throws TException {
      List includeFeature = new ArrayList();
      List excludeFeature = new ArrayList();
      SearchDataType searchDataType = null;
      Iterator var7 = hash.keySet().iterator();

      while(var7.hasNext()) {
         String key = (String)var7.next();
         SessionDetection sessionDetection = (SessionDetection)hash.get(key);
         searchDataType = sessionDetection.getSearchDataType();
         FeatureSearch featureSearch = new FeatureSearch(ByteBuffer.wrap(Base64Utils.decodeFromString(sessionDetection.getMeta().getFeature())), sessionDetection.getMeta().getResult());
         log.info("===>传给大数据的检索特征:{}", sessionDetection.getMeta().getFeature());
         if (sessionDetection.getFeatureType()) {
            includeFeature.add(featureSearch);
         } else {
            excludeFeature.add(featureSearch);
         }
      }

      log.info("includes={}", includeFeature);
      log.info("encludes={}", excludeFeature);
      NewImageSearchCondition searchCondition = new NewImageSearchCondition();
      BeanUtils.copyProperties(featureSearchParam, searchCondition);
      searchCondition.setExcludeFeature(excludeFeature);
      searchCondition.setIncludeFeature(includeFeature);
      long startTime = System.currentTimeMillis();
      log.info("调用大数据以图搜图类型：{}", searchDataType.name());
      List imageSearchResults = this.searchResult(searchDataType, searchCondition);
      log.info("调用大数据以图搜图耗时：{}ms", System.currentTimeMillis() - startTime);
      return Pair.of(searchDataType, imageSearchResults);
   }

   private Pair<SearchDataType, List<ImageSearchResult>> queryBigDataByFeature(FeatureSearchParam featureSearchParam) throws TException {
      List includeFeature = new ArrayList();
      List excludeFeature = new ArrayList();
      SearchDataType searchDataType = SearchDataType.FACE;
      List mapList = new ArrayList();
      FeatureSearch featureSearch = new FeatureSearch(ByteBuffer.wrap(Base64Utils.decodeFromString(featureSearchParam.getFeature())), mapList);
      includeFeature.add(featureSearch);
      NewImageSearchCondition searchCondition = new NewImageSearchCondition();
      BeanUtils.copyProperties(featureSearchParam, searchCondition);
      searchCondition.setExcludeFeature(excludeFeature);
      searchCondition.setIncludeFeature(includeFeature);
      List imageSearchResults = this.searchResult(searchDataType, searchCondition);
      return Pair.of(searchDataType, imageSearchResults);
   }

   private Pair queryBigData(Map hash, FileSearchParam fileSearchParam) throws TException {
      List includeFeature = new ArrayList();
      List excludeFeature = new ArrayList();
      SearchDataType searchDataType = null;
      Iterator var7 = hash.keySet().iterator();

      SessionDetection conditionR;
      while(var7.hasNext()) {
         String key = (String)var7.next();
         conditionR = (SessionDetection)hash.get(key);
         searchDataType = conditionR.getSearchDataType();
         FeatureSearch featureSearch = new FeatureSearch(ByteBuffer.wrap(Base64Utils.decodeFromString(conditionR.getMeta().getFeature())), conditionR.getMeta().getResult());
         if (conditionR.getFeatureType()) {
            includeFeature.add(featureSearch);
         } else {
            excludeFeature.add(featureSearch);
         }
      }

      FileSearchCondition searchCondition = new FileSearchCondition();
      SearchImageCondition conditionF = null;
//      conditionR = null;
      if (fileSearchParam.getFileParam() != null) {
         conditionF = new SearchImageCondition();
         BeanUtils.copyProperties(fileSearchParam.getFileParam(), conditionF);
         String fileIds = conditionF.getCameraId();
         if (StringUtils.isEmpty(fileIds)) {
            WebResInfo webResInfo = this.feign.getFileIds();
            if ("200".equals(webResInfo.getCode())) {
               new ArrayList();
               String jsonString = JSON.toJSONString(webResInfo.getData());
               List list = JSON.parseArray(jsonString, String.class);
               conditionF.setCameraId(StringUtils.join(list.toArray(), ","));
            }
         }
      }

      searchCondition.setExcludeFeature(excludeFeature);
      searchCondition.setIncludeFeature(includeFeature);
      searchCondition.setFileCondition(conditionF);
      searchCondition.setReadCondition(null);

      List imageSearchResults;
      try {
         long startTime = System.currentTimeMillis();
         imageSearchResults = this.searchResultForFile(searchDataType, searchCondition);
         log.info("调用大数据以图搜图耗时：{}ms", System.currentTimeMillis() - startTime);
      } catch (Exception var14) {
         log.error("调用大数据第三方数据失败：{0}", var14.getMessage());
         throw new WebResException("499", "大数据服务异常");
      }

      return Pair.of(searchDataType, imageSearchResults);
   }

   private List<ResourceResult> queryData(final SearchDataType type, final List<ImageSearchResult> imageSearchResults, final FeatureSearchParam featureSearchParam) {
      Integer returnSize = 0;
      Integer pageSize = 0;
      List resourceParams = Lists.newArrayList();
      List subResourceParams = Lists.newArrayList();
      Map scoreMaps = Maps.newHashMap();
      List bigdataList = Lists.newArrayList();
      boolean isFilter = !SearchDataType.VEHICLE.equals(type);
      if (imageSearchResults != null) {
         this.sortBigDataReturnData(imageSearchResults);
         Iterator var11 = imageSearchResults.iterator();

         while(var11.hasNext()) {
            ImageSearchResult result = (ImageSearchResult)var11.next();
            String logNum = result.getLogNum();
            resourceParams.add(new ResourceParam(logNum));
            scoreMaps.put(logNum, (BigDecimal.valueOf(result.getScore())).setScale(this.aggregatorProperties.getScoreAccuracy(), ScoreRoundingMode.fromMode(this.aggregatorProperties.getScoreRoundingMode()).getRoundingMode()).doubleValue());
            bigdataList.add(result.getLogNum() + result.getGatherTime());
         }

         returnSize = resourceParams.size();
         if (returnSize > this.aggregatorProperties.getShowBigDataImgResultNum()) {
            pageSize = this.aggregatorProperties.getShowBigDataImgResultNum();
         } else {
            pageSize = returnSize;
         }

         subResourceParams = resourceParams.subList(0, pageSize);
         log.warn("大数据以图搜图查询结果size------>{}", returnSize);
         log.warn("大数据以图搜图查询结果截取大小:{}", subResourceParams.size());
      }

      log.info("大数据原始:" + imageSearchResults);
      log.info("相似度精度:" + this.aggregatorProperties.getScoreAccuracy() + ",相似度舍入方式:" + ScoreRoundingMode.fromMode(this.aggregatorProperties.getScoreRoundingMode()) + ",scoreMaps:" + scoreMaps);
      Map<ResourceDefined.ResourceType,List<ResourceParam>> map = Maps.newHashMap();
      map.put(ResourceType.valueOf(type.name()), subResourceParams);
      long startTime = System.currentTimeMillis();
      List fetch = this.aggregatorService.fetch(map);
      log.info("类型[{}] 以图搜图结果根据id从opaq查询耗时{}ms", type.name(), System.currentTimeMillis() - startTime);
      Iterator iterator = fetch.iterator();

      while(true) {
         while(iterator.hasNext()) {
            ResourceResult next = (ResourceResult)iterator.next();
            Map data = next.getData();
            Long absTime = null;
            if (data.get("absTime") != null) {
               absTime = data.get("absTime") instanceof BigDecimal ? ((BigDecimal)data.get("absTime")).longValue() : (Long)data.get("absTime");
            }

            if (absTime != null && (absTime < featureSearchParam.getStartTime() || absTime > featureSearchParam.getEndTime())) {
               log.info("过滤掉的数据的时间---->{}", absTime);
               iterator.remove();
            } else {
               String recordId = (String)data.get(ResourceInnerFiled._RECORD_ID.getFiled());
               data.put("score", scoreMaps.get(recordId));
               String key = recordId + absTime;
               if (isFilter && !bigdataList.contains(key)) {
                  iterator.remove();
               }
            }
         }

         this.sortFetchData(fetch);
         log.info("过滤后页面返回大小：{}", fetch.size());
         return fetch;
      }
   }

   private List queryDataForFile(SearchDataType type, List imageSearchResults) {
      List list = new ArrayList();
      Map scoreMaps = Maps.newLinkedHashMap();
      if (imageSearchResults == null) {
         return list;
      } else if (imageSearchResults.size() <= 0) {
         return list;
      } else {
         Iterator var5 = imageSearchResults.iterator();

         while(var5.hasNext()) {
            ImageSearchResult result = (ImageSearchResult)var5.next();
            String logNum = result.getLogNum();
            scoreMaps.put(logNum, (BigDecimal.valueOf(result.getScore())).setScale(this.aggregatorProperties.getScoreAccuracy(), ScoreRoundingMode.fromMode(this.aggregatorProperties.getScoreRoundingMode()).getRoundingMode()).doubleValue());
         }

         List listIds = new ArrayList(scoreMaps.keySet());

         try {
            List result = this.getImgList(type, listIds);
            log.info("调用后端接口查询后的结果size={}", result.size());
            Iterator var15 = scoreMaps.keySet().iterator();

            while(var15.hasNext()) {
               String id = (String)var15.next();
               Iterator var9 = result.iterator();

               while(var9.hasNext()) {
                  AllStructureVo allStructureVo = (AllStructureVo)var9.next();
                  if (id.equals(allStructureVo.getRecordId())) {
                     AllStructureVo item = new AllStructureVo();
                     BeanUtils.copyProperties(allStructureVo, item);
                     if (scoreMaps.containsKey(allStructureVo.getRecordId())) {
                        item.setScore(scoreMaps.get(allStructureVo.getRecordId() == null ? "" : allStructureVo.getRecordId()).toString());
                     }

                     list.add(item);
                  }
               }
            }

            return list;
         } catch (Exception var12) {
            log.error("调用第三方文件结构化服务失败：" + var12.getMessage());
            throw new WebResException("499", "调用第三方数据失败");
         }
      }
   }

   private List getImgList(SearchDataType type, List recordIds) {
      List list = new ArrayList();
      new WebResInfo();
      if (recordIds.size() <= 0) {
         return list;
      } else {
         WebResInfo webResInfo;
         try {
            long startTime = System.currentTimeMillis();
            SearchData searchData = SearchDataFactory.getSearchData(type);
            webResInfo = searchData.getImgList(recordIds, this.feign);
            log.info("调用文件结构化以图搜图耗时：{}ms", System.currentTimeMillis() - startTime);
         } catch (Exception var8) {
            log.error("文件结构化服务失败" + var8.getMessage());
            throw new WebResException("499", "文件结构化服务器异常");
         }

         if ("200".equals(webResInfo.getCode())) {
            String jsonString = JSON.toJSONString(webResInfo.getData());
            list = JSON.parseArray(jsonString, AllStructureVo.class);
         }

         return list;
      }
   }

   private List searchResultForFile(SearchDataType dataType, FileSearchCondition searchCondition) throws TException {
      switch (dataType) {
         case BODY:
            return this.humanSearchImageClient.searchImgListByImg(searchCondition);
         case VEHICLE:
            VehicleFileSearchCondition vehicleFileSearchCondition = new VehicleFileSearchCondition();
            BeanUtils.copyProperties(searchCondition, vehicleFileSearchCondition);
            vehicleFileSearchCondition.setIncludeFeature(this.crateVehicleInputRecord(searchCondition, true));
            vehicleFileSearchCondition.setExcludeFeature(this.crateVehicleInputRecord(searchCondition, false));
            log.info("车辆以图搜图接口参数：" + vehicleFileSearchCondition);
            return this.vehicleSearchImageClient.searchImgListByImg(vehicleFileSearchCondition);
         case NONMOTOR:
            return this.nonmotorVehicleClient.searchImgListByImg(searchCondition);
         default:
            return new ArrayList();
      }
   }

   private void sortBigDataReturnData(List result) {
      Collections.sort(result, new Comparator<ImageSearchResult>() {
         public int compare(ImageSearchResult r1, ImageSearchResult r2) {
            Double score1 = r1.getScore();
            Double score2 = r2.getScore();
            if (score1 != null && score2 != null) {
               if (score1.compareTo(score2) == 0) {
                  Long absTime1 = r1.getGatherTime();
                  Long absTime2 = r2.getGatherTime();
                  if (absTime1 != null && absTime2 != null) {
                     return -1 * absTime1.compareTo(absTime2);
                  }
               }

               return -1 * score1.compareTo(score2);
            } else {
               return 1;
            }
         }
      });
   }

   private void sortFetchData(List fetch) {
      if (fetch != null && !fetch.isEmpty()) {
         Collections.sort(fetch, new Comparator<ResourceResult>() {
            public int compare(ResourceResult r1, ResourceResult r2) {
               if (r1 != null && r2 != null) {
                  Double score1 = Double.valueOf(Objects.toString(r1.getData().get("score"), "-1.0"));
                  Double score2 = Double.valueOf(Objects.toString(r2.getData().get("score"), "-1.0"));
                  if (score1 != null && score2 != null) {
                     if (score1.compareTo(score2) == 0) {
                        Long absTime1 = r1.getData().get("absTime") instanceof BigDecimal ? ((BigDecimal)r1.getData().get("absTime")).longValue() : (Long)r1.getData().get("absTime");
                        Long absTime2 = r2.getData().get("absTime") instanceof BigDecimal ? ((BigDecimal)r2.getData().get("absTime")).longValue() : (Long)r2.getData().get("absTime");
                        if (absTime1 != null && absTime2 != null) {
                           return -1 * absTime1.compareTo(absTime2);
                        }

                        try {
                           Date passTime1 = DateUtils.parseDate((String)r1.getData().get("passTime"), "yyyy-MM-dd HH:mm:ss");
                           Date passTime2 = DateUtils.parseDate((String)r2.getData().get("passTime"), "yyyy-MM-dd HH:mm:ss");
                           if (passTime1 != null && passTime2 != null) {
                              return -1 * passTime1.compareTo(passTime2);
                           }
                        } catch (ParseException var9) {
                           ImgSearchServiceImpl.log.error("车辆数据时间格式化错误", var9);
                        }
                     }

                     return -1 * score1.compareTo(score2);
                  } else {
                     return 1;
                  }
               } else {
                  return 1;
               }
            }
         });
      }
   }

   private Pair detectAllTypes(byte[] imgByte, String type, String position) throws PccHandleException {
      DataModel.Roi roi = null;
      if (StringUtils.isNoneBlank(position)) {
         ImagePosition imagePosition = this.getImagePosition(position);
         roi = new DataModel.Roi(imagePosition.getLeft(), imagePosition.getTop(), imagePosition.getRight(), imagePosition.getBottom());
      }

      DetectResult detectResult = null;
      SearchDataType searchDataType = null;

      try {
         if (StringUtils.isBlank(type) || SearchDataType.FACE.name().equals(type)) {
            searchDataType = SearchDataType.FACE;
            DetectFaceParam build = DetectFaceParam.create().feature(FeatureSwitch.EXTRACT).roi(roi).build();
            detectResult = this.PccDetectClient.detectFace(imgByte, build);
         }
      } catch (Exception var11) {
         log.warn("提取不到人脸特征");
      }

      DetectBodyVehicleParam vehicleBuild;
      try {
         if (StringUtils.isBlank(type) && detectResult == null || SearchDataType.BODY.name().equals(type)) {
            vehicleBuild = DetectBodyVehicleParam.create(OBJType.BODY, FeatureType.BODY).detect(DetectSwitch.DETECT).roi(roi).build();
            searchDataType = SearchDataType.BODY;
            detectResult = this.PccDetectClient.detectBodyVehicle(imgByte, vehicleBuild);
         }
      } catch (Exception var10) {
         log.warn("提取不到人体特征");
      }

      try {
         if (StringUtils.isBlank(type) && detectResult == null || SearchDataType.VEHICLE.name().equals(type)) {
            searchDataType = SearchDataType.VEHICLE;
            if (this.structureTaskConfigProperties.getStructureVehicleType().equals("DEEPLINT")) {
               vehicleBuild = DetectBodyVehicleParam.create(OBJType.VEHICLE, FeatureType.VEHICLE).detect(DetectSwitch.DETECT).roi(roi).build();
               detectResult = this.PccDetectClient.detectBodyVehicle(imgByte, vehicleBuild);
            } else {
               ImageStructProcess param = ImageStructProcess.buildVehicleParam().build();
               detectResult = this.PccDetectClient.detectImageStrucSingle(imgByte, param, ImageStruType.Vehicle);
            }
         }
      } catch (Exception var9) {
         log.warn("提取不到车辆特征");
      }

      try {
         if (StringUtils.isBlank(type) && detectResult == null || SearchDataType.NONMOTOR.name().equals(type)) {
            searchDataType = SearchDataType.NONMOTOR;
            if (this.structureTaskConfigProperties.getStructureVehicleType().equals("DEEPLINT")) {
               vehicleBuild = DetectBodyVehicleParam.create(OBJType.NONMOTOR, FeatureType.NONMOTOR).detect(DetectSwitch.DETECT).roi(roi).build();
               detectResult = this.PccDetectClient.detectBodyVehicle(imgByte, vehicleBuild);
            }
         }
      } catch (Exception var8) {
         log.info(var8.getMessage());
         log.warn("提取不到非机动车特征");
      }

      if (detectResult == null) {
         throw new PccHandleException("图片没有特征");
      } else {
         return Pair.of(searchDataType, detectResult);
      }
   }

   public byte[] convertMultipartFileToBytes(MultipartFile file) {
      try {
         return file.getBytes();
      } catch (IOException var3) {
         throw new WebResException("400");
      }
   }

   private byte[] searchByLog(SearchDataType dataType, SearchFeatureCondition searchFeatureCondition) throws TException {
      try {
         switch (dataType) {
            case BODY:
               return this.humanSearchImageClient.searchByLogNew(searchFeatureCondition);
            case VEHICLE:
               return null;
            case NONMOTOR:
               return this.nonmotorVehicleClient.searchByLogNew(searchFeatureCondition);
            case FACE:
               return this.faceSearchImageClient.searchByLogNew(searchFeatureCondition);
         }
      } catch (Exception var4) {
         log.error("{}类型记录编号[{}]搜特征失败,重新提取图片特征", dataType.name(), searchFeatureCondition.getLogNum());
      }

      return null;
   }

   private List searchResult(SearchDataType dataType, NewImageSearchCondition searchCondition) throws TException {
      switch (dataType) {
         case BODY:
            return this.humanSearchImageClient.searchByImgNew(searchCondition);
         case VEHICLE:
            NewVehicleSearchCondition newVehicleSearchCondition = new NewVehicleSearchCondition();
            BeanUtils.copyProperties(searchCondition, newVehicleSearchCondition);
            String timeFormat = "yyyyMMdd";
            newVehicleSearchCondition.setVehicleStartTimeStr(DateFormatUtils.format(searchCondition.getStartTime(), timeFormat));
            newVehicleSearchCondition.setVehicleEndTimeStr(DateFormatUtils.format(searchCondition.getEndTime(), timeFormat));
            newVehicleSearchCondition.setIncludeFeature(this.crateVehicleInputRecord(searchCondition, true));
            newVehicleSearchCondition.setExcludeFeature(this.crateVehicleInputRecord(searchCondition, false));
            return this.vehicleSearchImageClient.searchByImgNew(newVehicleSearchCondition);
         case NONMOTOR:
            return this.nonmotorVehicleClient.searchByImgNew(searchCondition);
         case FACE:
            return this.faceSearchImageClient.searchByImgNew(searchCondition);
         default:
            return null;
      }
   }

   private List crateVehicleInputRecord(FileSearchCondition fileSearchCondition, boolean flag) {
      List list = flag ? fileSearchCondition.getIncludeFeature() : fileSearchCondition.getExcludeFeature();
      return this.createInputRecord(list);
   }

   private List crateVehicleInputRecord(NewImageSearchCondition searchCondition, boolean flag) {
      List list = flag ? searchCondition.getIncludeFeature() : searchCondition.getExcludeFeature();
      return this.createInputRecord(list);
   }

   private List createInputRecord(List featureSearches) {
      List vehicleInputRecordList = new ArrayList();
      VehicleInputRecord vehicleInputRecord;
      if (featureSearches != null && !featureSearches.isEmpty()) {
         for(Iterator var4 = featureSearches.iterator(); var4.hasNext(); vehicleInputRecordList.add(vehicleInputRecord)) {
            FeatureSearch featureSearch = (FeatureSearch)var4.next();
            vehicleInputRecord = new VehicleInputRecord();
            vehicleInputRecord.setFeature(featureSearch.getFeature());
            List attribute = featureSearch.getAttribute();
            if (!CollectionUtils.isEmpty(attribute)) {
               VehicleAttrVo vehicleAttr = this.getVehicleAttr(attribute);
               vehicleInputRecord.setClpp(vehicleAttr.getClpp());
               vehicleInputRecord.setCsys(vehicleAttr.getCsys());
            }
         }
      }

      return vehicleInputRecordList;
   }

   private VehicleAttrVo getVehicleAttr(List attribute) {
      Map attrMap = (Map)attribute.get(0);
      String clpp = null;
      int csys = 0;
      Map modelType;
      if (this.structureTaskConfigProperties.getStructureVehicleType().equals("DEEPLINT")) {
         modelType = (Map)attrMap.get("ModelType");
         clpp = (String)((Map)VehicleAttrContext.attrMap.get(VehicleAttrContext.AttrEnum.VehicleBrand)).get(String.valueOf(((Double)modelType.get("BrandId")).intValue()));
         clpp = clpp == null ? "-1" : clpp;
      } else {
         modelType = (Map)attrMap.get("Brand");
         Object nBrand = modelType.get("nBrand");
         if (nBrand != null) {
            clpp = String.valueOf(nBrand);
            clpp = clpp.substring(0, clpp.indexOf("."));
         }
      }

      return new VehicleAttrVo(clpp, csys);
   }

   private ImagePosition getImagePosition(String position) {
      if (!position.matches("(\\d{1,}\\.){3,}\\d{1,}")) {
         throw new WebResException("图像坐标信息传参有误");
      } else {
         String[] rois = position.split("\\.");
         return new ImagePosition(Integer.parseInt(rois[0]), Integer.parseInt(rois[1]), Integer.parseInt(rois[2]), Integer.parseInt(rois[3]));
      }
   }

   private String cutImage(String image, String position) throws ImageServerException {
      ImagePosition imagePosition = this.getImagePosition(position);
      return this.imageServerClient.cutImage(image, imagePosition.getLeft(), imagePosition.getRight(), imagePosition.getTop(), imagePosition.getBottom());
   }

   public DetectedResult detectAllFeature(FeatureDetectParam featureDetectParam) throws PccHandleException, TException {
      log.warn("------------->开始提取特征");
      long startTime = System.currentTimeMillis();
      String position = featureDetectParam.getPosition();
      String sessionKey = featureDetectParam.getSessionKey();
      MultipartFile file = featureDetectParam.getFile();
      String featureImg = featureDetectParam.getImgPath();
      new HashMap();
      Map detectResultMap;
      byte[] imgByte;
      if (StringUtils.isNotBlank(featureImg)) {
         imgByte = this.imageServerClient.downloadImage(featureImg).getData();
         detectResultMap = this.detectAllTypeFeaturesFromImage(imgByte, featureDetectParam.getType(), position);
      } else {
         if (file == null) {
            throw new WebResException("499", "文件和文件路径不能同时为空");
         }

         try {
            imgByte = file.getBytes();
         } catch (IOException var21) {
            throw new WebResException("499", "请上传文件");
         }

         featureImg = this.imageServerClient.uploadImage(imgByte);
         detectResultMap = this.detectAllTypeFeaturesFromImage(imgByte, featureDetectParam.getType(), position);
      }

      if (StringUtils.isNoneBlank(position)) {
         featureImg = this.cutImage(featureImg, position);
      }

      DetectedResult detectedResult = new DetectedResult();
      new ArrayList();
      Iterator var12;
      if (!detectResultMap.isEmpty()) {
         var12 = detectResultMap.entrySet().iterator();

         while(var12.hasNext()) {
            Map.Entry entry = (Map.Entry)var12.next();
            Iterator var14 = ((List)entry.getValue()).iterator();

            while(var14.hasNext()) {
               DetectResult detectResult1 = (DetectResult)var14.next();
               String dataKey = this.sessionManager.generKeyIfNoExist(featureDetectParam.getDataKey());
               sessionKey = this.setSessionCache(sessionKey, dataKey, new SessionDetection((SearchDataType)entry.getKey(), detectResult1, featureDetectParam.getFeatureType()));

               DetectedResult.DetectInfo detectInfo;
               for(Iterator var17 = detectResult1.getResult().iterator(); var17.hasNext(); detectedResult.getDetectResultMap().add(detectInfo)) {
                  Map map = (Map)var17.next();
                  detectInfo = new DetectedResult.DetectInfo();
                  detectInfo.setDataKey(dataKey);
                  detectInfo.setDataType((SearchDataType)entry.getKey());
                  Map posMap;
                  if (entry.getKey().equals(SearchDataType.FACE) && map.get("Pos") != null) {
                     posMap = (Map)map.get("Pos");
                     detectInfo.setPosition(this.wrapPccFacePosition(posMap));
                  }

                  if (entry.getKey().equals(SearchDataType.BODY) && map.get("Pos") != null) {
                     posMap = (Map)map.get("Pos");
                     detectInfo.setPosition(this.wrapDeepBodyPosition(posMap));
                  }

                  if (entry.getKey().equals(SearchDataType.VEHICLE) && map.get("Img") != null) {
                     posMap = (Map)map.get("Img");
                     detectInfo.setPosition(this.wrapVehiclePosition(posMap));
                  }

                  if (entry.getKey().equals(SearchDataType.NONMOTOR) && map.get("Img") != null) {
                     posMap = (Map)map.get("Img");
                     detectInfo.setPosition(this.wrapVehiclePosition(posMap));
                  }
               }

               detectedResult.setImgPath(featureImg);
               detectedResult.setSessionKey(sessionKey);
               detectedResult.setFeature(detectResult1.getFeature());
            }
         }
      }

      this.sort(detectedResult.getDetectResultMap());
      var12 = detectedResult.getDetectResultMap().iterator();

      while(var12.hasNext()) {
         DetectedResult.DetectInfo detectInfo = (DetectedResult.DetectInfo)var12.next();
         log.info("dataKey={},dataType={}", detectInfo.getDataKey(), detectInfo.getDataType());
      }

      log.warn("------------->结束提取特征，耗时：{}ms", System.currentTimeMillis() - startTime);
      return detectedResult;
   }

   private void sort(List detectInfoList) {
      Collections.sort(detectInfoList, new Comparator<DetectedResult.DetectInfo>() {
         public int compare(DetectedResult.DetectInfo o1, DetectedResult.DetectInfo o2) {
            int order = ImgSearchServiceImpl.this.getSearchDataType(o1.getDataType()) > ImgSearchServiceImpl.this.getSearchDataType(o2.getDataType()) ? 1 : (ImgSearchServiceImpl.this.getSearchDataType(o1.getDataType()) == ImgSearchServiceImpl.this.getSearchDataType(o2.getDataType()) ? 0 : -1);
            return order;
         }
      });
   }

   private int getSearchDataType(SearchDataType searchDataType) {
      int type = 0;
      switch (searchDataType) {
         case BODY:
            type = 1;
            break;
         case VEHICLE:
            type = 2;
            break;
         case NONMOTOR:
            type = 3;
            break;
         case FACE:
            type = 0;
      }

      return type;
   }

   private String wrapPccFacePosition(Map posMap) {
      log.info("start face position {}", posMap);
      if (posMap.get("Left") instanceof Double) {
         return this.wrapPccFacePositionForDoubleOri(posMap);
      } else {
         return posMap.get("Left") instanceof Integer ? this.wrapPccFacePositionForIntegerOri(posMap) : "";
      }
   }

   private String wrapPccFacePositionForDoubleOri(Map posMap) {
      Double left = (Double)posMap.get("Left");
      Double top = (Double)posMap.get("Top");
      Double right = (Double)posMap.get("Right");
      Double bottom = (Double)posMap.get("Bottom");
      StringBuilder pos = new StringBuilder();
      pos.append(left.intValue()).append(",").append(top.intValue()).append(",").append(right.intValue()).append(",").append(bottom.intValue());
      log.info("face position={}", pos);
      return pos.toString();
   }

   private String wrapPccFacePositionForIntegerOri(Map posMap) {
      Integer left = (Integer)posMap.get("Left");
      Integer top = (Integer)posMap.get("Top");
      Integer right = (Integer)posMap.get("Right");
      Integer bottom = (Integer)posMap.get("Bottom");
      StringBuilder pos = new StringBuilder();
      pos.append(left).append(",").append(top).append(",").append(right).append(",").append(bottom);
      log.info("face position={}", pos);
      return pos.toString();
   }

   private String wrapDeepBodyPosition(Map posMap) {
      Integer left = (Integer)posMap.get("Left");
      Integer top = (Integer)posMap.get("Top");
      Integer right = (Integer)posMap.get("Right");
      Integer bottom = (Integer)posMap.get("Bottom");
      StringBuilder pos = new StringBuilder();
      pos.append(left).append(",").append(top).append(",").append(right).append(",").append(bottom);
      log.info("body postion={}", pos);
      return pos.toString();
   }

   private String wrapVehiclePosition(Map positionMap) {
      log.info("positionMap={}", positionMap);
      Map posMap = (Map)positionMap.get("Cutboard");
      log.info("posMap={}", posMap);
      Double left = (Double)posMap.get("X");
      Double top = (Double)posMap.get("Y");
      Double right = (Double)posMap.get("Width") + left;
      Double bottom = (Double)posMap.get("Height") + top;
      StringBuilder builder = new StringBuilder();
      builder.append(left.intValue()).append(",").append(top.intValue()).append(",").append(right.intValue()).append(",").append(bottom.intValue());
      log.info("vehicle position={}", builder);
      return builder.toString();
   }

   public FeatureSearchParam excludeUnselectedFeatures(ExcludeCondition excludeCondition) {
      String sessionKey = null;
      FeatureSearchParam featureSearchParams = new FeatureSearchParam();
      log.info("sessionKey={}", excludeCondition.getSessionKey());
      if (!StringUtils.isNotBlank(excludeCondition.getSessionKey())) {
         throw new WebResException("400");
      } else {
         sessionKey = excludeCondition.getSessionKey();
         LinkedHashMap cache = this.sessionManager.getValue(excludeCondition.getSessionKey());
         if (cache != null) {
            log.info("before remove cacheSet={}", cache.keySet());
            List excludedDataKeyList = new ArrayList();
            if (org.apache.commons.lang.StringUtils.isNotBlank(excludeCondition.getExcludedDataKeys())) {
               excludedDataKeyList = Arrays.asList(excludeCondition.getExcludedDataKeys().split(","));
            }

            Iterator var6 = excludedDataKeyList.iterator();

            while(var6.hasNext()) {
               String dataKey = (String)var6.next();
               log.info("remove dataKey={}", dataKey);
               cache.remove(dataKey);
            }

            this.sessionManager.setValue(sessionKey, cache);
            log.info("after remove dataKey cacheSet={}", cache.keySet());
         }

         featureSearchParams.setSessionKey(excludeCondition.getSessionKey());
         return featureSearchParams;
      }
   }

   public JSONObject checkFace(File image, String commandType, String detectType, String userToken) {
      JSONObject result = new JSONObject();
      String userAuthUrl = "/FaceDynamicServer/search/checkFace";
      MultipartEntity entity = new MultipartEntity();

      try {
         FileBody fileBody = new FileBody(image);
         entity.addPart("image", fileBody);
         entity.addPart("commandType", new StringBody(commandType));
         entity.addPart("detectType", new StringBody(detectType));
         CloseableHttpResponse closeableHttpResponse = this.httpRequestClient(userAuthUrl, entity, null, userToken);
         int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
         if (statusCode == 200) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            if (null != httpEntity) {
               String retSrc = EntityUtils.toString(httpEntity);
               JSONObject jsonObject = JSONObject.parseObject(retSrc);
               int code = (Integer)jsonObject.get("code");
               String message = (String)jsonObject.get("message");
               result.put("code", code);
               result.put("message", message);
               JSONObject jsonObjectData;
               if (200 != code && 4023 != code) {
                  if (4022 == code) {
                     result.put("message", "未检测到人脸");
                     jsonObjectData = new JSONObject();
                     jsonObjectData.put("imgPath", this.uploadImage(image, userToken));
                     result.put("data", jsonObjectData);
                  }
               } else {
                  jsonObjectData = new JSONObject();
                  JSONObject dataJsonObject = (JSONObject)jsonObject.get("data");
                  String imageUrl = (String)dataJsonObject.get("imageurl");
                  if (4023 == code) {
                     imageUrl = this.uploadImage(image, userToken);
                  }

                  imageUrl = imageUrl.startsWith("a") ? imageUrl.substring(1) : imageUrl;
                  String imagePrefix = this.aggregatorProperties.getPortraitPictureUrlPrefix();
                  jsonObjectData.put("imgPath", imagePrefix + imageUrl);
                  String taskId = (String)dataJsonObject.get("key");
                  jsonObjectData.put("taskId", taskId);
                  JSONArray faceInfoArray = (JSONArray)dataJsonObject.get("faceInfo");
                  JSONArray detectResultMapArray = new JSONArray();

                  for(int i = 0; i < faceInfoArray.size(); ++i) {
                     JSONObject faceInfoSubObject = (JSONObject)faceInfoArray.get(i);
                     JSONObject rectJsonObject = (JSONObject)faceInfoSubObject.get("rect");
                     int bottom = (Integer)rectJsonObject.get("bottom");
                     int left = (Integer)rectJsonObject.get("left");
                     int right = (Integer)rectJsonObject.get("right");
                     int top = (Integer)rectJsonObject.get("top");
                     JSONObject detectResultMapObject = new JSONObject();
                     detectResultMapObject.put("position", left + "," + top + "," + right + "," + bottom);
                     detectResultMapArray.add(detectResultMapObject);
                  }

                  jsonObjectData.put("detectResultMap", detectResultMapArray);
                  result.put("data", jsonObjectData);
               }
            } else {
               result.put("code", 500);
               result.put("message", "人脸检测接口请求异常, httpEntity为空");
            }
         } else {
            result.put("code", statusCode);
            result.put("message", "人脸检测接口请求异常");
         }
      } catch (Exception var31) {
         var31.printStackTrace();
         result.put("code", 500);
         result.put("message", "人脸检测接口异常,e:" + var31.getMessage());
      }

      return result;
   }

   public JSONObject detectFace(PortraitCondition portraitCondition) {
      JSONObject result = new JSONObject();
      String detectFaceUrl = "/FaceDynamicServer/search/detectFace";
      String imagePrefix = this.aggregatorProperties.getPortraitPictureUrlPrefix();
      portraitCondition.setImageurl("a" + portraitCondition.getImageurl().replace(imagePrefix, ""));
      String json = JSON.toJSONString(portraitCondition);

      try {
         StringEntity entity = new StringEntity(json);
         CloseableHttpResponse closeableHttpResponse = this.httpRequestClient(detectFaceUrl, null, entity, portraitCondition.getUserToken());
         int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
         if (statusCode == 200) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            if (null != httpEntity) {
               String retSrc = EntityUtils.toString(httpEntity);
               JSONObject jsonObject = JSONObject.parseObject(retSrc);
               int code = (Integer)jsonObject.get("code");
               String message = (String)jsonObject.get("message");
               JSONObject dataObjecct = (JSONObject)jsonObject.get("data");
               String taskId = (String)dataObjecct.get("key");
               String imgPath = (String)dataObjecct.get("imageurl");
               result.put("code", code);
               result.put("message", message);
               result.put("taskId", taskId);
               result.put("imgPath", imgPath);
            } else {
               result.put("code", 500);
               result.put("message", "特征提取接口请求异常, httpEntity为空");
            }
         } else {
            result.put("code", statusCode);
            result.put("message", "特征提取接口请求异常");
         }
      } catch (Exception var17) {
         result.put("code", 500);
         result.put("message", "特征提取异常,e:" + var17.getMessage());
      }

      return result;
   }

   public JSONObject portraitImageSearch(PortraitSearchCondition portraitSearchConditions) {
      JSONObject result = new JSONObject();
      String imgSearchUrl = "/FaceDynamicServer/sync/search/searchaccesslog";
      String imagePrefix = this.aggregatorProperties.getPortraitPictureUrlPrefix();
      portraitSearchConditions.setImagePath(portraitSearchConditions.getImagePath().replace(imagePrefix, ""));
      String searchJson = JSON.toJSONString(portraitSearchConditions);

      try {
         StringEntity stringEntity = new StringEntity(searchJson);
         CloseableHttpResponse closeableHttpResponse = this.httpRequestClient(imgSearchUrl, null, stringEntity, portraitSearchConditions.getUserToken());
         int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
         if (200 == statusCode) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            if (null != httpEntity) {
               String retSrc = EntityUtils.toString(httpEntity);
               JSONObject jsonObject = JSONObject.parseObject(retSrc);
               int code = (Integer)jsonObject.get("code");
               result.put("code", code);
               String message = (String)jsonObject.get("message");
               result.put("message", message);
               JSONObject data = (JSONObject)jsonObject.get("data");
               DataBean dataBean = JSON.toJavaObject(data, DataBean.class);
               JSONArray jsonArray = this.dataConvert(dataBean);
               result.put("data", jsonArray);
            } else {
               result.put("code", 500);
               result.put("message", "以图搜图接口异常, httpEntity为空");
            }
         } else {
            result.put("code", statusCode);
            result.put("message", "以图搜图接口异常");
         }
      } catch (Exception var17) {
         var17.printStackTrace();
      }

      return result;
   }

   private JSONArray dataConvert(DataBean dataBean) {
      JSONArray array = new JSONArray();
      List resultBeans = dataBean.getResult();
      if (null != resultBeans && resultBeans.size() > 0) {
         for(int i = 0; i < resultBeans.size(); ++i) {
            JSONObject object = new JSONObject();
            new HashMap();
            DataBean.ResultBean resultBean = (DataBean.ResultBean)resultBeans.get(i);
            Long date = 0L;

            try {
               date = DateUtils.parseDate(resultBean.getAccessLog().getLogTime(), "yy-MM-dd HH:mm:ss").getTime();
            } catch (Exception var10) {
               var10.printStackTrace();
            }

            object.put("_absTime", date);
            object.put("_recordId", resultBean.getAccessLog().getID());
            object.put("age", resultBean.getAccessLog().getAge());
            object.put("attractive", resultBean.getAccessLog().getAttractive());
            object.put("confidence", resultBean.getAccessLog().getFaceConfidence());
            object.put("deviceId", resultBean.getCamera().getID());
            object.put("deviceName", resultBean.getCamera().getName());
            object.put("eyeGlass", resultBean.getAccessLog().getGlass());
            object.put("sunGlass", resultBean.getAccessLog().getGlass());
            object.put("gender", resultBean.getAccessLog().getGender().equals("Women") ? 1 : 0);
            object.put("mask", resultBean.getAccessLog().getMask());
            object.put("recordId", resultBean.getAccessLog().getID());
            object.put("traitImg", resultBean.getAccessLog().getFacePath());
            object.put("sceneImg", resultBean.getAccessLog().getScenePath());
            object.put("score", resultBean.getScore());
            JSONObject data = new JSONObject();
            data.put("data", object);
            array.add(data);
         }
      }

      return array;
   }

   public JSONObject userAuth(String userName, String password) {
      JSONObject result = new JSONObject();

      try {
         String userAuthUrl = "/FaceDynamicServer/user/auth";
         MultipartEntity entity = new MultipartEntity();
         entity.addPart("username", new StringBody(userName));
         entity.addPart("password", new StringBody(DigestUtils.md5Hex(password)));
         CloseableHttpResponse closeableHttpResponse = this.httpRequestClient(userAuthUrl, entity, null, "");
         int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
         if (statusCode == 200) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            if (null != httpEntity) {
               String retSrc = EntityUtils.toString(httpEntity);
               JSONObject jsonObject = JSONObject.parseObject(retSrc);
               int code = (Integer)jsonObject.get("code");
               String message = (String)jsonObject.get("message");
               result.put("code", code);
               result.put("message", message);
               if (200 == code) {
                  JSONObject dataJsonObject = (JSONObject)jsonObject.get("data");
                  JSONObject userJsonObject = (JSONObject)dataJsonObject.get("JsonUserData");
                  String userToken = (String)userJsonObject.get("UserKey");
                  result.put("userToken", userToken);
               }
            } else {
               result.put("code", 500);
               result.put("message", "访问人像系统获取token异常");
            }
         } else {
            result.put("code", statusCode);
            result.put("message", "获取token出错");
         }
      } catch (Exception var16) {
         var16.printStackTrace();
         result.put("code", 500);
         result.put("message", "访问人像系统获取token异常");
      }

      return result;
   }

   public String uploadImage(File image, String userToken) {
      String uploadImgUrl = "/FaceDynamicServer/search/uploadImage";
      MultipartEntity entity = new MultipartEntity();
      String imgUrl = "";

      try {
         FileBody fileBody = new FileBody(image);
         entity.addPart("image", fileBody);
         CloseableHttpResponse closeableHttpResponse = this.httpRequestClient(uploadImgUrl, entity, null, userToken);
         int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
         if (statusCode == 200) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            if (null != httpEntity && null != httpEntity) {
               String retSrc = EntityUtils.toString(httpEntity);
               JSONObject jsonObject = JSONObject.parseObject(retSrc);
               imgUrl = (String)jsonObject.get("data");
               log.info("====================>图片上传成功，imageUrl=" + imgUrl);
            }
         }
      } catch (Exception var12) {
         log.error("====================>图片上传异常:e:" + var12.getMessage());
         var12.printStackTrace();
      }

      return imgUrl;
   }

   public CloseableHttpResponse httpRequestClient(String url, MultipartEntity multipartEntity, StringEntity stringEntity, String userToken) {
      String prefix = this.aggregatorProperties.getPortraitHttpRequestUrlPrefix();
      String httpRequestUrl = prefix + url;
      log.info("=================>http请求链接为:" + httpRequestUrl);
      CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
      CloseableHttpResponse httpResponse = null;
      HttpPost httpPost = new HttpPost(httpRequestUrl);
      httpPost.addHeader("AuthCacheKey", userToken);
      httpPost.addHeader("Content-type", "application/json");
      httpPost.setEntity(multipartEntity);
      if (null != stringEntity) {
         httpPost.setEntity(stringEntity);
      }

      try {
         httpResponse = closeableHttpClient.execute(httpPost);
         log.info("==========>httpResponse:" + httpResponse);
      } catch (Exception var11) {
         log.error("http请求出现异常，e:" + var11.getMessage());
         var11.printStackTrace();
      }

      return httpResponse;
   }

   private Map detectAllTypeFeaturesFromImage(byte[] imgByte, String type, String position) throws PccHandleException {
      Map detectResultMap = new HashMap();
      DataModel.Roi roi = null;
      if (StringUtils.isNoneBlank(position)) {
         ImagePosition imagePosition = this.getImagePosition(position);
         roi = new DataModel.Roi(imagePosition.getLeft(), imagePosition.getTop(), imagePosition.getRight(), imagePosition.getBottom());
      }

      List detectResult = null;
      SearchDataType searchDataType = null;

      long startTimeNonmotor;
      try {
         if (this.isSwitchOn(SearchDataType.FACE.getIntValue()) && (StringUtils.isBlank(type) || SearchDataType.FACE.name().equalsIgnoreCase(type))) {
            log.warn("--->开始提取人脸特征");
            startTimeNonmotor = System.currentTimeMillis();
            searchDataType = SearchDataType.FACE;
            DetectFaceParam build = DetectFaceParam.create().feature(FeatureSwitch.EXTRACT).roi(roi).filterRule(FilterRuleSwitch.ALL_FACE).build();
            detectResult = this.PccDetectClient.detectFaceList(imgByte, build);
            if (detectResult != null) {
               detectResultMap.put(SearchDataType.FACE, detectResult);
            }

            log.warn("--->结束提取人脸特征，耗时:{}ms", System.currentTimeMillis() - startTimeNonmotor);
         }
      } catch (Exception var14) {
         log.warn("提取不到人脸特征");
      }

      DetectBodyVehicleParam vehicleBuild;
      try {
         if (this.isSwitchOn(SearchDataType.BODY.getIntValue()) && (StringUtils.isBlank(type) || SearchDataType.BODY.name().equalsIgnoreCase(type))) {
            log.warn("--->开始提取人体特征");
            startTimeNonmotor = System.currentTimeMillis();
            vehicleBuild = DetectBodyVehicleParam.create(OBJType.BODY, FeatureType.BODY).detect(DetectSwitch.DETECT).roi(roi).build();
            searchDataType = SearchDataType.BODY;
            detectResult = this.PccDetectClient.detectBodyVehicleList(imgByte, vehicleBuild);
            if (detectResult != null) {
               detectResultMap.put(SearchDataType.BODY, detectResult);
            }

            log.warn("--->结束提取人体特征，耗时:{}ms", System.currentTimeMillis() - startTimeNonmotor);
         }
      } catch (Exception var13) {
         log.warn("提取不到人体特征");
      }

      try {
         if (this.isSwitchOn(SearchDataType.VEHICLE.getIntValue()) && (StringUtils.isBlank(type) || SearchDataType.VEHICLE.name().equalsIgnoreCase(type))) {
            log.warn("--->开始提取机动车特征");
            startTimeNonmotor = System.currentTimeMillis();
            searchDataType = SearchDataType.VEHICLE;
            if (this.structureTaskConfigProperties.getStructureVehicleType().equals("DEEPLINT")) {
               vehicleBuild = DetectBodyVehicleParam.create(OBJType.VEHICLE, FeatureType.VEHICLE).detect(DetectSwitch.DETECT).roi(roi).build();
               detectResult = this.PccDetectClient.detectBodyVehicleList(imgByte, vehicleBuild);
               if (detectResult != null) {
                  detectResultMap.put(SearchDataType.VEHICLE, detectResult);
               }
            } else {
               VehicleGPUParam vehicleBuild1 = VehicleGPUParam.create().roi(roi).build();
               detectResult = this.PccDetectClient.detectVehicleGPUList(imgByte, vehicleBuild1);
               if (detectResult != null) {
                  detectResultMap.put(SearchDataType.VEHICLE, detectResult);
               }
            }

            log.warn("--->结束提取机动车特征，耗时:{}ms", System.currentTimeMillis() - startTimeNonmotor);
         }
      } catch (Exception var12) {
         log.warn("提取不到车辆特征");
      }

      try {
         if (this.isSwitchOn(SearchDataType.NONMOTOR.getIntValue()) && (StringUtils.isBlank(type) || SearchDataType.NONMOTOR.name().equalsIgnoreCase(type))) {
            log.warn("--->开始提取非机动车特征");
            startTimeNonmotor = System.currentTimeMillis();
            if (this.structureTaskConfigProperties.getStructureVehicleType().equals("DEEPLINT")) {
               vehicleBuild = DetectBodyVehicleParam.create(OBJType.NONMOTOR, FeatureType.NONMOTOR).detect(DetectSwitch.DETECT).roi(roi).build();
               detectResult = this.PccDetectClient.detectBodyVehicleList(imgByte, vehicleBuild);
               if (detectResult != null) {
                  detectResultMap.put(SearchDataType.NONMOTOR, detectResult);
               }
            }

            log.warn("--->结束提取非机动车特征，耗时:{}ms", System.currentTimeMillis() - startTimeNonmotor);
         }
      } catch (Exception var11) {
         log.warn("非机动车提取特征失败");
         log.info(var11.getMessage());
      }

      if (detectResult == null) {
         log.warn("图片没有特征");
      }

      return detectResultMap;
   }

   private boolean isSwitchOn(int type) {
      int structureTypeSwitch = this.aggregatorProperties.getStructureTypeSwitch();
      return (structureTypeSwitch & type) == type;
   }
}
